package net.hubt.itc.util;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import net.hubt.itc.data.RssItems;

public class RssParseHandler extends DefaultHandler  {
	private List<RssItems> rssItems;
	private RssItems currentItem;
	private boolean parsingTitle;
	private boolean parsingLink;
	private boolean parsingDescription;
	
	public RssParseHandler() {
		rssItems = new ArrayList<RssItems>();
	}
	public List<RssItems> getItems() {
		return rssItems;
	}
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		if ("item".equals(qName)) {
			currentItem = new RssItems();
		} else if ("title".equals(qName)) {
			parsingTitle = true;
		} else if ("link".equals(qName)) {
			parsingLink = true;
		}else if("description".equals(qName))
		{
			parsingDescription=true;
		}
	}
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		if ("item".equals(qName)) {
			rssItems.add(currentItem);
			currentItem = null;
		} else if ("title".equals(qName)) {
			parsingTitle = false;
		} else if ("link".equals(qName)) {
			parsingLink = false;
		}else if ("description".equals(qName)) {
			parsingDescription = false;
		}
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		if (parsingTitle) {
			if (currentItem != null)
				currentItem.setTitle(new String(ch, start, length));
		} else if (parsingLink) {
			if (currentItem != null) {
				currentItem.setLink(new String(ch, start, length));
				parsingLink = false;
			}
		}else if(parsingDescription)
		{
			if(currentItem!=null)
			{
				currentItem.setDescription(new String(ch,start,length));
			}
		}
	}
	
}
